package dao.impl;

import dao.UserDao;
import org.apache.ibatis.session.SqlSession;
import pojo.User;
import utils.MyBatisUtil;

import java.util.List;

public class UserDaoImpl implements UserDao {
    @Override
    public List<User> findAll(User user,int offset,int pageSize) {
        /*// 引入mybatis配置文件
        String resource = "mybatis-config.xml";
        SqlSession sqlSession = null;
        //加载配置文件
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream(resource);
            //创建会话工厂
            SqlSessionFactory sqlSessionFactory = new org.apache.ibatis.session.SqlSessionFactoryBuilder().build(resourceAsStream);
            //创建会话
            sqlSession = sqlSessionFactory.openSession();
            //执行查询
            List<User> users = sqlSession.getMapper(UserDao.class).findAll();
            //返回查询对象
            return users;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            sqlSession.close();
        }*/
        return MyBatisUtil.getSession().getMapper(UserDao.class).findAll(user,offset,pageSize);
    }



    @Override
    public int addUser(User user) {
        SqlSession session = MyBatisUtil.getSession();
        int result = session.getMapper(UserDao.class).addUser(user);
        session.commit();
        return result;
    }

    @Override
    public User findUserById(int id) {
        return MyBatisUtil.getSession().getMapper(UserDao.class).findUserById(id);
    }

    public int updateUser(User user) {
        SqlSession session = MyBatisUtil.getSession();
        int result = session.getMapper(UserDao.class).updateUser(user);
        session.commit();
        return result;
    }

    @Override
    public int deleteUserById(int id) {
        SqlSession session = MyBatisUtil.getSession();
        int result = session.getMapper(UserDao.class).deleteUserById(id);
        session.commit();
        return result;
    }

    @Override
    public int count(User user) {
        return MyBatisUtil.getSession().getMapper(UserDao.class).count(user);
    }
}
